    //
//  CedarBaseRequestForUploadFile.m
//  CedarFinancialPlanner
//
//  Created by lshenrong on 2018/5/25.
//  Copyright © 2018年 cedarhd. All rights reserved.
//

#import "CedarBaseRequestForUploadFile.h"
#import "PlatformTools.h"
#import "YTKNetworkConfig.h"
#import "CedarTools.h"
#import "CedarBaseResponse.h"
#import "CedarDataBaseStore.h"
#import "CedarTipsManager.h"
#import "NetworkManager.h"

@interface CedarBaseRequestForUploadFile()

@property (nonatomic,strong) CedarBaseResponse * _Nullable cedarResponse;


@end


@implementation CedarBaseRequestForUploadFile
- (instancetype)init{
    if (self = [super init]) {
        self.isNotShowErrorTips = NO;
        self.isNotUseToken = NO;
    }
    return self;
}

- (NSTimeInterval)requestTimeoutInterval{
    return 15;
}

- (YTKRequestMethod)requestMethod {
    return YTKRequestMethodPOST;
}


- (CedarBaseResponse *)cedarResponse{
    if (!_cedarResponse) {
        _cedarResponse = [[CedarBaseResponse alloc]init];
    }
    return _cedarResponse;
}


- (void)requestCompleteFilter{
    [super requestCompleteFilter];
#if DEBUG
    NSString * str  =[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    BigCLog(@"%@ response for upload file: \n%@\n",NSStringFromClass([self class]),str);
    
#endif
//    if ([self isKindOfClass:[LoginAPI class]]) {
//        NSString *token = self.responseHeaders[@"token"];
//        if (token) {
//            [[CedarDataBaseStore shareInstance] setTokenForAppConfige:token];
//            CLog(@"token :%@",token);
//        }
//    }
  //  self.cedarResponse.dataObject = self.responseString;
    {
        NSError *error;
        NSDictionary *dict2 = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dict = dict2;
        if([dict isKindOfClass: [NSDictionary class] ]) {
            self.cedarResponse.serialNumber = [dict objectForKey:@"serialNumber"];
            NSNumber *codeNumber = [dict objectForKey:@"code"];
            self.cedarResponse.code = codeNumber.integerValue;
            self.cedarResponse.msg = [dict objectForKey:@"msg"];
            if (self.cedarResponse.code == ResponseTypeScuess) {   
                self.cedarResponse.dataObject = [dict objectForKey:@"data"];
            }else{
                if(self.cedarResponse.code == ResponseTypeTokenExpired){//token失效 回到首页
                    [[CedarDataBaseStore shareInstance] setTokenForAppConfige:nil];
                    [[CedarDataBaseStore shareInstance] saveLoginInfo:nil];
                    [self publish:Logout_Notification data:nil];
                }
                if (!self.isNotShowErrorTips){
                    if ([self.cedarResponse.msg length]>0) {
                        [CedarTipsManager showTipsInWindowWithOnlyText:self.cedarResponse.msg];
                    }
                }
            }
        }
    }
}

- (void)requestFailedFilter{
    [super requestFailedFilter];
    if (!self.isCancelled){
        if (!self.isNotShowErrorTips) {
            //[CedarTipsManager showTipsInWindowWithOnlyText:@"当前网络不佳，请稍后再试!"];
        }
    }
}

- (void)startCedarRequestWithCompletionBlock:(nullable CedarRequestCompletionBlock)result{
    [self startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (result) {
            result(self.cedarResponse);
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (result) {
            result(self.cedarResponse);
        }
    }];
}

- (id)requestAppendArgument{
    return @{};
}

#pragma mark - custom url

- (id)requestArgument{
    
    NSString  *serialNumber =  [PlatformTools deviceGUID];
    NSString *channel = @"ios";
    NSString *requestTime = [PlatformTools getCurrentTime];
    NSString *requestHost = [[NetworkManager shareInstance]currentDeviceIP];
    NSString  *encyptSTr = @"";
    NSString *appVersion = [PlatformTools appVersion];
    NSDictionary *appDic = [self requestAppendArgument];
    NSDictionary * arguDict = nil;
    NSString *token =  [[CedarDataBaseStore shareInstance] getTokenForAppConfige];
    AvoidNullString(token);
    
    if (appDic) {
        NSString *appdendJsonStr =  [CedarTools dictToJsonStr:appDic];
#if DEBUG
        NSString *token1 =  [[CedarDataBaseStore shareInstance] getTokenForAppConfige];
        CLog(@"%@,url:%@,请求参数:%@,token:%@",NSStringFromClass([self class]),[self requestUrl],appdendJsonStr,token1);
#endif
        encyptSTr =  [CedarTools encyptAES128PKCS5:appdendJsonStr withKey:(NSString *)CedarAES128Key];
        arguDict = @{@"serialNumber":serialNumber,
                     @"channel":channel,
                     @"requestTime":requestTime,
                     @"version":appVersion,
                     @"requestHost":requestHost,
                     @"token":token,
                    @"flag":@(1),
                     @"body":encyptSTr
                     };
    }else{
        arguDict = @{@"serialNumber":serialNumber,
                     @"channel":channel,
                     @"requestTime":requestTime,
                     @"version":appVersion,
                      @"token":token,
                      @"flag":@(1),
                     @"requestHost":requestHost
                     };
    }
    return arguDict;
}


- (void)dealloc{
    #if DEBUG
    CLog(@"请求类  %@ 销毁了 ",NSStringFromClass([self class]));
    #endif
}

@end
